const app = getApp();
Page({
  data: {
    server:app.globalData.server,
    api:app.globalData.api,
    adList:[
      {path:"../../assets/img/data/banner1.jpg"},
      {path:"../../assets/img/data/banner2.png"},
      {path:"../../assets/img/data/banner3.jpg"}
    ],
    memberAdList:[
      {path:"../../assets/img/data/member-ad4.jpg"},
      {path:"../../assets/img/data/member-ad5.jpg"},
      {path:"../../assets/img/data/member-ad6.jpg"}
    ],
    goodsClassify:[],//商品分类
    allTypeId:0,
    currentIndexCla:0,
    goodsList:{
      total:null,
      page: 1,
      list:[],
      show: true,
    },
    isLogin:false,
    token:'',
    userId:null,
    dataEnd:false
  },
  onShow() {
    this.getProductTypeData();
    // 页面显示
    let that = this;
    my.getStorage({
      key: 'userInfo',
      success: function(res) {
        that.setData({
          isLogin:res.data?true:false,
          token:res.data?res.data.token:'',
          userId:res.data?res.data.userInfo.id:null,
          goodsList:{
            total:null,
            page: 1,
            list:[],
            show: true,
          },
          dataEnd:false
        })
        //调商品列表的接口
        that.mySchedulde()
        console.log(that.data.token)
      }
    });
  },
  // 点击分类
  changeClassify(e){
    let typeId = e.target.dataset.index
    this.setData({
      currentIndexCla: typeId,
      goodsList:{
        total:null,
        page: 1,
        list:[],
        show: true,
      },
      dataEnd:false
    })
    this.mySchedulde()
  },
  onShareAppMessage(e){
    try{
      let productId = e.target.dataset.key;
      return {
        desc: '我刚刚跟你分享了一件好物，快来看看吧',
        path: 'pages/detail/detail?pid='+this.data.userId+'&index='+productId,
        success:function(res){
          console.log(res)
        }
      }
    }catch(err){
      console.log(err)
    }
  },
  bindShare(){
    if(!this.data.isLogin){
      my.reLaunch({ url: '../login/login' });
      return false
    }else{
      this.onShareAppMessage()
    }
  },
  getProductTypeData(){
    let that = this;
    my.request({
      url: this.data.api+'/product/type',
      method: 'get',
      headers:{'content-type':'application/json'},  //默认值
      dataType: 'json',
      success: function(res) {
        if(res.data.errCode==0){
          that.setData({
            goodsClassify: res.data.result
          })
        }
      }
    });
  },
  //scroll-view滑到底部触发事件
  async scrollMytrip() {
    try {
      if(this.data.token){
        let result = await this.getTokenStatus();
        if(!this.data.isLogin){
          my.reLaunch({ url: '../login/login' });
          return false
        }
      }
      let page = this.data.goodsList.page;
      let list =  this.data.goodsList.list
      // 判断是否还有数据需要加载
      if (list.length < this.data.goodsList.total) {
        this.data.goodsList.show = true;
        let newPage = page + 1;
        this.mySchedulde(newPage);
      }else{
        this.setData({
          dataEnd:true
        })
      }
    } catch (e) {
      this.data.goodsList.show = false;
      console.log('scrollMytrip执行异常:', e);
    }
  },
  mySchedulde(page = 1) {
    try {
      let url = this.data.currentIndexCla?this.data.api+'/product?page='+page+'&typeId='+this.data.currentIndexCla:this.data.api+'/product?page='+page;
      let list = this.data.goodsList.list;
      let that = this;
      my.request({
        url:url,
        method: 'get',
        headers:{
          'content-type':'application/json',
          'token':this.data.token
        },
        dataType: 'json',
        success: function(res) {
          console.log(res);
          try{
            if(res.data.data.result && !res.data.data.result[0].level){
              my.removeStorage({
                key: 'userInfo'
              });
              that.setData({
                isLogin:false,
                token:'',
                userId:null,
                dataEnd:false
              })
            }
          }catch(err){
            console.log(err);
          }
          if(res.data.errCode==0){
            if(res.data.data.result.length>0){
              let data = res.data.data.result;
              for (let i = 0; i < data.length; i++) {
                list.push(data[i]);
              }
              that.setData({
                goodsList:{
                  total:res.data.data.total_count,
                  page: page,
                  list:list,
                  show: false,
                  dataEnd:false
                },
              })
            }
          }
        }
      });
    } catch (e) {
      console.log('mySchedulde执行异常:', e);
    }
  },
  getTokenStatus(){
    return new Promise((resolve, reject) => {
      let that = this;
      my.request({
        url:this.data.api+'/checkToken',
        method: 'get',
        headers:{
          'content-type':'application/json',
          'token':this.data.token
        },
        dataType: 'json',
        success: function(res) {
          console.log(res)
          if(res.data.errCode==9){//token过期
            my.removeStorage({
              key: 'userInfo'
            });
            that.setData({
              isLogin:false,
              token:'',
              userId:null,
              dataEnd:false
            })
            my.showToast({
              type: 'exception',
              content: res.data.message,
              duration: 2000
            });
          }
          resolve()
        }
      });
    })
  }
});

